package com.hexus.eve.actions.security;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.hexus.eve.entities.Account;
import com.hexus.eve.entities.security.User;
import com.hexus.eve.utils.CurrentUser;


/**
 * This bean is called right after successful authentication.
 * It is used for updating accounts of the user authenticated.
 * 
 * @author Mikhail_Berastau
 */
public class PostSuccessfulAuthenticationHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Autowired
	SessionFactory sessionFactory;
	
	private Logger log = Logger.getLogger(this.getClass());
	
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
		//Synchronizing statuses of all user's accounts
		User user = CurrentUser.getUser();
		
		List<Account> accounts = user.getAccounts();
		if(log.isDebugEnabled()) {
			log.debug("Synchronizing accounts of user " + user.getUsername());
		}

		for(Account a : accounts) {
			a.updateAvailabilityStatus();
			a.synchronizeWithEve(sessionFactory);
		}
		
		super.onAuthenticationSuccess(request, response, authentication);
	}
}
